package com.tangkun.environment.activity;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.tangkun.environment.R;
import com.tangkun.environment.adapter.WuRanYuanAdapter;
import com.tangkun.environment.adapter.WuRanYuanPopupWindowAdapter;
import com.tangkun.environment.entity.gongzuo.DepartmentChildReturn;
import com.tangkun.environment.entity.gongzuo.EnterpriseReturn;
import com.tangkun.environment.network.MySubscribe;
import com.tangkun.environment.rx.RxActivityHelper;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.utils.LogUtils;
import com.tangkun.environment.utils.SharePrefercesUtils;
import com.tangkun.environment.view.CustomListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 污染源 列表
 * flag 1全部污染源 2附近污染源
 */

public class WuRanYuanActivity extends BaseActivity implements CustomListView.OnLoadMoreListener, CustomListView.OnRefreshListener {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.right)
    ImageView right;
    @BindView(R.id.custom_list_view)
    CustomListView customListView;
    @BindView(R.id.tv_wuranyuan_jiedaoban)
    TextView tvWuranyuanJiedaoban;
    @BindView(R.id.iv_wuranyuan_jiedaoban)
    ImageView ivWuranyuanJiedaoban;
    @BindView(R.id.ll_wuranyuan_jiedaoban)
    LinearLayout llWuranyuanJiedaoban;
    @BindView(R.id.tv_wuranyuan_shequ)
    TextView tvWuranyuanShequ;
    @BindView(R.id.iv_wuranyuan_shequ)
    ImageView ivWuranyuanShequ;
    @BindView(R.id.ll_wuranyuan_shequ)
    LinearLayout llWuranyuanShequ;
    @BindView(R.id.tv_wuranyuan_zhongheti)
    TextView tvWuranyuanZhongheti;
    @BindView(R.id.iv_wuranyuan_zhongheti)
    ImageView ivWuranyuanZhongheti;
    @BindView(R.id.ll_wuranyuan_zhongheti)
    LinearLayout llWuranyuanZhongheti;
    @BindView(R.id.ll_wuranyuan_tab)
    LinearLayout llWuranyuanTab;
    @BindView(R.id.view_wuranyuan_tab_underline)
    View viewWuranyuanTabUnderline;
    private Context mContext;

    /**
     * 数据源
     */
    private List<EnterpriseReturn.DataBean.ListBean> dataList = new ArrayList<EnterpriseReturn.DataBean.ListBean>();
    /**
     * 适配器
     */
    private WuRanYuanAdapter adapter;
    /**
     * 筛选PopupWindow
     */
    private PopupWindow mPopWindow;
    /**
     * 污染源列表请求参数
     */
    private Map<String, String> map = new HashMap<>();

    /**
     * 街道办选中ID
     */
    private String streetid = "";
    /**
     * 社区ID
     */
    private String communityid = "";
    /**
     * 综合体ID
     */
    private String propertyid = "";

    /**
     * 筛选的ID
     */
    private String ids = "";

    public int page = 1;// 当前页
    private int totalCount = 0;// 总数量
    private boolean OnHeadRefreshTAG = true;// 为true时清楚已有数据

    /**
     * 选中项 根据selectedIndex来判断调用那个接口
     */
    private int selectedIndex = -1;

    /**
     * 审核过来的owner参数为1
     */
    private String owner = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        owner = getIntent().getStringExtra("owner");
        setContentView(R.layout.activity_wuranyuan);
        ButterKnife.bind(this);
        initView();
        title.setText("全部污染源");
        right.setImageResource(R.mipmap.ic_daohanglan_ditumoshi);
        queryByOrgEnterprise(selectedIndex);
    }

    private void initView() {
        customListView.setOnRefreshListener(this);
        customListView.setOnLoadListener(this);
        customListView.setCanLoadMore(true);
        customListView.setAutoLoadMore(true);
        adapter = new WuRanYuanAdapter(WuRanYuanActivity.this, dataList);
        customListView.setAdapter(adapter);
    }

    @Override
    public void onRefresh() {
        page = 1;
        OnHeadRefreshTAG = true;
        customListView.setCanLoadMore(true);
        queryByOrgEnterprise(selectedIndex);
    }

    @Override
    public void onLoadMore() {
        OnHeadRefreshTAG = false;
        if (page * pageSize < totalCount) {
            page++;
            queryByOrgEnterprise(selectedIndex);
        } else {
            customListView.onLoadMoreCompleteNoData();
        }
    }

    @OnClick({R.id.back, R.id.right, R.id.ll_wuranyuan_jiedaoban, R.id.ll_wuranyuan_shequ, R.id.ll_wuranyuan_zhongheti})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                JumpHelper.finish(mContext);
                break;
            case R.id.right:
                JumpHelper.jump(WuRanYuanActivity.this, LocationDemo2.class, false);
                break;
            case R.id.ll_wuranyuan_jiedaoban://街道办
                if (dataListPopupwindow1 != null && dataListPopupwindow1.size() > 0) {
                    selectedIndex = 0;
                    showPopupWindow(selectedIndex);
                } else {
                    selectedIndex = 0;
                    departmentChild(selectedIndex, "");
                }
                break;
            case R.id.ll_wuranyuan_shequ://社区
                if (dataListPopupwindow1 == null || dataListPopupwindow1.size() == 0 || TextUtils.isEmpty(streetid)) {
                    showToast("请先选择街道办");
                    return;
                }

                if (dataListPopupwindow2 != null && dataListPopupwindow2.size() > 0) {
                    selectedIndex = 1;
                    showPopupWindow(selectedIndex);
                } else {
                    selectedIndex = 1;
                    departmentChild(selectedIndex, streetid);
                }
                break;
            case R.id.ll_wuranyuan_zhongheti://综合体
                if (dataListPopupwindow1 == null || dataListPopupwindow1.size() == 0 || TextUtils.isEmpty(streetid)) {
                    showToast("请先选择街道办");
                    return;
                }

                if (dataListPopupwindow3 != null && dataListPopupwindow3.size() > 0) {
                    selectedIndex = 2;
                    showPopupWindow(selectedIndex);
                } else {
                    selectedIndex = 2;
                    departmentChild(selectedIndex, streetid);
                }

//                if (dataListPopupwindow2 == null || dataListPopupwindow2.size() == 0 || TextUtils.isEmpty(communityid)) {
//                    showToast("请选择社区");
//                    return;
//                }
//                if (dataListPopupwindow3 != null && dataListPopupwindow3.size() > 0) {
//                    showPopupWindow(2);
//                } else {
//                    departmentChild(2, communityid);
//                }
                break;
        }
    }


    /**
     * 初始化顶部选中的筛选状态
     *
     * @param selectedIndex 选中的索引 0：性别 1：年龄 2：原发病/改成了治疗方式 3：植管日期
     */

    private void initTopTab(int selectedIndex) {
        switch (selectedIndex) {
            case 0://街道办
                tvWuranyuanJiedaoban.setTextColor(getResources().getColor(R.color.common_hint));
                tvWuranyuanShequ.setTextColor(getResources().getColor(R.color.common_hint));
                tvWuranyuanZhongheti.setTextColor(getResources().getColor(R.color.common_hint));
                ivWuranyuanJiedaoban.setImageResource(R.mipmap.ic_shang_hui);
                ivWuranyuanShequ.setImageResource(R.mipmap.ic_xia_hui);
                ivWuranyuanZhongheti.setImageResource(R.mipmap.ic_xia_hui);
                break;
            case 1://社区
                tvWuranyuanJiedaoban.setTextColor(getResources().getColor(R.color.common_hint));
                tvWuranyuanShequ.setTextColor(getResources().getColor(R.color.common_hint));
                tvWuranyuanZhongheti.setTextColor(getResources().getColor(R.color.common_hint));
                ivWuranyuanJiedaoban.setImageResource(R.mipmap.ic_xia_hui);
                ivWuranyuanShequ.setImageResource(R.mipmap.ic_shang_hui);
                ivWuranyuanZhongheti.setImageResource(R.mipmap.ic_xia_hui);
                break;
            case 2://综合体
                tvWuranyuanJiedaoban.setTextColor(getResources().getColor(R.color.common_hint));
                tvWuranyuanShequ.setTextColor(getResources().getColor(R.color.common_hint));
                tvWuranyuanZhongheti.setTextColor(getResources().getColor(R.color.common_hint));
                ivWuranyuanJiedaoban.setImageResource(R.mipmap.ic_xia_hui);
                ivWuranyuanShequ.setImageResource(R.mipmap.ic_xia_hui);
                ivWuranyuanZhongheti.setImageResource(R.mipmap.ic_shang_hui);
                break;
            default://都未选中
                tvWuranyuanJiedaoban.setTextColor(getResources().getColor(R.color.common_hint));
                tvWuranyuanShequ.setTextColor(getResources().getColor(R.color.common_hint));
                tvWuranyuanZhongheti.setTextColor(getResources().getColor(R.color.common_hint));
                ivWuranyuanJiedaoban.setImageResource(R.mipmap.ic_xia_hui);
                ivWuranyuanShequ.setImageResource(R.mipmap.ic_xia_hui);
                ivWuranyuanZhongheti.setImageResource(R.mipmap.ic_xia_hui);
                break;
        }
    }

    //顶部筛选条件的控件
    LinearLayout bg;
    ListView listview;
    //数据源 街道办
    List<DepartmentChildReturn.DataBean> dataListPopupwindow1 = new ArrayList<DepartmentChildReturn.DataBean>();
    //数据源 社区
    List<DepartmentChildReturn.DataBean> dataListPopupwindow2 = new ArrayList<DepartmentChildReturn.DataBean>();
    //数据源 综合体
    List<DepartmentChildReturn.DataBean> dataListPopupwindow3 = new ArrayList<DepartmentChildReturn.DataBean>();

    /**
     * 展示筛选PopupWindow
     *
     * @param selectedIndex 选中的索引 0：街道办 1：社区 2：综合体
     */
    private void showPopupWindow(final int selectedIndex) {
        //设置contentView
        View contentView = LayoutInflater.from(WuRanYuanActivity.this).inflate(R.layout.popuwindow_wuranyuan, null);
        mPopWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        mPopWindow.setContentView(contentView);
        // 初始化控件
        listview = (ListView) contentView.findViewById(R.id.listview);

        WuRanYuanPopupWindowAdapter adapter = null;
        //当前选中项
        switch (selectedIndex) {
            case 0://街道办
                adapter = new WuRanYuanPopupWindowAdapter(WuRanYuanActivity.this, dataListPopupwindow1);
                break;
            case 1://社区
                adapter = new WuRanYuanPopupWindowAdapter(WuRanYuanActivity.this, dataListPopupwindow2);
                break;
            case 2://综合体
                adapter = new WuRanYuanPopupWindowAdapter(WuRanYuanActivity.this, dataListPopupwindow3);
                break;
            default://
                break;
        }
        listview.setAdapter(adapter);

        //列表监听事件
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                //当前选中项
                switch (selectedIndex) {
                    case 0://街道办
                        //清空后面的数据
                        dataListPopupwindow2 = new ArrayList<DepartmentChildReturn.DataBean>();
                        dataListPopupwindow3 = new ArrayList<DepartmentChildReturn.DataBean>();
                        tvWuranyuanShequ.setText("社区");
                        tvWuranyuanZhongheti.setText("综合体");

                        //设置选中项
                        for (int i = 0; i < dataListPopupwindow1.size(); i++) {
                            dataListPopupwindow1.get(i).isSelected = false;
                        }
                        dataListPopupwindow1.get(position).isSelected = true;

                        streetid = dataListPopupwindow1.get(position).ids;
                        //置空后面社区、综合体ID
                        communityid = "";
                        propertyid = "";
                        if (!TextUtils.isEmpty(dataListPopupwindow1.get(position).names)) {
                            tvWuranyuanJiedaoban.setText(dataListPopupwindow1.get(position).names + "");
                        } else {
                            tvWuranyuanJiedaoban.setText("");
                        }
                        ids = dataListPopupwindow1.get(position).ids;

                        page = 1;
                        OnHeadRefreshTAG = true;
                        customListView.setCanLoadMore(true);
                        customListView.setSelection(0);
                        queryByOrgEnterprise(selectedIndex);
                        mPopWindow.dismiss();
                        break;
                    case 1://社区
                        //清空后面的数据
                        dataListPopupwindow3 = new ArrayList<DepartmentChildReturn.DataBean>();
                        tvWuranyuanZhongheti.setText("综合体");

                        //设置选中项
                        for (int i = 0; i < dataListPopupwindow2.size(); i++) {
                            dataListPopupwindow2.get(i).isSelected = false;
                        }
                        dataListPopupwindow2.get(position).isSelected = true;

                        communityid = dataListPopupwindow2.get(position).ids;
                        //置空后面综合体ID
                        propertyid = "";
                        ids = dataListPopupwindow2.get(position).ids;
                        if (!TextUtils.isEmpty(dataListPopupwindow2.get(position).names)) {
                            tvWuranyuanShequ.setText(dataListPopupwindow2.get(position).names + "");
                        } else {
                            tvWuranyuanShequ.setText("");
                        }

                        page = 1;
                        OnHeadRefreshTAG = true;
                        customListView.setCanLoadMore(true);
                        customListView.setSelection(0);
                        queryByOrgEnterprise(selectedIndex);
                        mPopWindow.dismiss();
                        break;
                    case 2://综合体
                        //设置选中项
                        for (int i = 0; i < dataListPopupwindow3.size(); i++) {
                            dataListPopupwindow3.get(i).isSelected = false;
                        }
                        dataListPopupwindow3.get(position).isSelected = true;

                        propertyid = dataListPopupwindow3.get(position).ids;
                        ids = dataListPopupwindow3.get(position).ids;
                        if (!TextUtils.isEmpty(dataListPopupwindow3.get(position).names)) {
                            tvWuranyuanZhongheti.setText(dataListPopupwindow3.get(position).names + "");
                        } else {
                            tvWuranyuanZhongheti.setText("");
                        }

                        page = 1;
                        OnHeadRefreshTAG = true;
                        customListView.setCanLoadMore(true);
                        customListView.setSelection(0);
                        queryByOrgEnterprise(selectedIndex);
                        mPopWindow.dismiss();
                        break;
                }
            }
        });

        //PopupWindow背景点击事件
        bg = (LinearLayout) contentView.findViewById(R.id.ll_popupwindow_bg);
        //背景点击事件
        bg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPopWindow.dismiss();
            }
        });

        //显示PopupWindow
        mPopWindow.setFocusable(true);
        mPopWindow.setOutsideTouchable(true);
        mPopWindow.setTouchable(true);

        mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopWindow.showAsDropDown(viewWuranyuanTabUnderline);
        //隐藏对话框时候把所有顶部tab颜色设置回初始颜色
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                initTopTab(-1);
            }
        });
    }

    /**
     * 污染源PopupWindow筛选列表
     *
     * @param selectedIndex 选中的索引 0：街道办 1：社区 2：综合体
     * @param ids           列表选中索引的ID
     */
    private void departmentChild(final int selectedIndex, final String ids) {
        Map<String, String> map = new HashMap<>();
        //当前选中项
        switch (selectedIndex) {
            case 0://街道办
                map.put("ids", "");
                map.put("type", "2");
                break;
            case 1://社区
                map.put("ids", ids);
                map.put("type", "3");
                break;
            case 2://综合体
                map.put("ids", ids);
                map.put("type", "4");
                break;
        }
        fromNetwork.departmentChild(map).compose(new RxActivityHelper<DepartmentChildReturn>().ioMain(WuRanYuanActivity.this, true))
                .subscribe(new MySubscribe<DepartmentChildReturn>(mContext, true) {
                    @Override
                    protected void success(DepartmentChildReturn resultBean) {
                        if (resultBean.data != null) {
                            //当前选中项
                            switch (selectedIndex) {
                                case 0://街道办
                                    dataListPopupwindow1.clear();
                                    dataListPopupwindow1.addAll(resultBean.data);
                                    showPopupWindow(selectedIndex);
                                    break;
                                case 1://社区
                                    dataListPopupwindow2.clear();
                                    dataListPopupwindow2.addAll(resultBean.data);
                                    showPopupWindow(selectedIndex);
                                    break;
                                case 2://综合体
                                    dataListPopupwindow3.clear();
                                    dataListPopupwindow3.addAll(resultBean.data);
                                    showPopupWindow(selectedIndex);
                                    break;
                                default://
                                    break;
                            }
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                    }
                });
    }

    /**
     * 污染源列表
     *
     * @param selectedIndex 选中的索引 0：街道办 1：社区 2：综合体
     */
    private void queryByOrgEnterprise(final int selectedIndex) {
        Map<String, String> map = new HashMap<>();
        map.put("pageNumber", page + "");
        map.put("pageSize", pageSize + "");
        //当前选中项
        switch (selectedIndex) {
            case 0://街道办
                map.put("streetid", streetid);
                break;
            case 1://社区
                map.put("streetid", streetid);
                map.put("communityid", communityid);
                break;
            case 2://综合体
                map.put("streetid", streetid);
                map.put("communityid", communityid);
                map.put("propertyid", propertyid);
                break;
            default://其他情况 不传递参数
                break;
        }
        map.put("lat", SharePrefercesUtils.getLatitude(mContext));
        map.put("lng", SharePrefercesUtils.getLongitude(mContext));
        //审核增加owner参数为1
        if (!TextUtils.isEmpty(owner)) {
            map.put("owner", owner);
        }
        LogUtils.e("" + map.toString());
        fromNetwork.queryByOrgEnterprise(map).compose(new RxActivityHelper<EnterpriseReturn>().ioMain(WuRanYuanActivity.this, true))
                .subscribe(new MySubscribe<EnterpriseReturn>(mContext, true) {
                    @Override
                    protected void success(EnterpriseReturn resultBean) {
                        if (resultBean.data != null) {
                            customListView.onLoadMoreComplete();
                            customListView.onRefreshComplete();
                            customListView.setCanLoadMore(true);
                            totalCount = resultBean.data.totalRow;
                            if (page * pageSize >= totalCount) {
                                customListView.setCanLoadMore(false);
                            }
                            //下拉刷新
                            if (OnHeadRefreshTAG) {
                                OnHeadRefreshTAG = false;
                                dataList.clear();
                            }
                            //填充数据
                            dataList.addAll(resultBean.data.list);
                            //刷新列表
                            adapter.notifyDataSetChanged();
//
//
//                            //清空数据
//                            dataList.clear();
//                            //填充数据
//                            dataList.addAll(resultBean.data.list);
//                            //刷新列表
//                            if (adapter == null) {
//                                adapter = new WuRanYuanAdapter(WuRanYuanActivity.this, dataList);
//                                customListView.setAdapter(adapter);
//                            } else {
//                                adapter.notifyDataSetChanged();
//                            }
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                    }
                });
    }
}
